package com.hang.ixin.netty;

import com.hang.ixin.Enums.ActionEnum;
import com.hang.ixin.Enums.MsgSignEnum;
import com.hang.ixin.POJO.ChatMsg;
import com.hang.ixin.POJO.DTO.ContentDTO;
import com.hang.ixin.POJO.DTO.MsgDTO;
import com.hang.ixin.SpringUtil;
import com.hang.ixin.service.UserService;
import com.hang.ixin.service.impl.UserServiceImpl;
import com.hang.ixin.utils.JsonUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;


public class Myhandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        //获取msg内容
        ContentDTO contentDTO = JsonUtils.jsonToPojo(msg.text(), ContentDTO.class);
        //判断action状态
        Integer action = contentDTO.getAction();
        //拿到当前channel
        Channel channel = ctx.channel();
        //初始化链接
        if (ActionEnum.CONNECT.getCode().equals(action)) {
            //把当前channel和senderid关联
            UserChannelMap.put(contentDTO.getMsgDTO().getSendUserId(), channel);



        } else if (ActionEnum.CHAT.getCode().equals(action)) {
            //将未读消息保存到数据库
            MsgDTO msgDTO = contentDTO.getMsgDTO();
            String accepter = msgDTO.getAcceptUserId();
            UserService userService = SpringUtil.getBean("userServiceImpl", UserServiceImpl.class);
            String msgid = userService.saveMsg(msgDTO);
            msgDTO.setMsgId(msgid);
            //将消息发送至accepter
            Channel accepterChannel = UserChannelMap.get(accepter);
            if (accepterChannel == null) {
                //TODO 消息推送
            } else {
                if (channels.find(accepterChannel.id()) != null) {
                    accepterChannel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objectToJson(msgDTO)));
                } else {
                    //TODO 消息推送
                }
            }

        } else if (ActionEnum.SIGNED.getCode().equals(action)) {
            //批量获取消息ID
            UserService userService = SpringUtil.getBean("userServiceImpl", UserServiceImpl.class);
            String idstr = contentDTO.getExtend();
            String[] ids = idstr.split(",");
            List<String> idList = new ArrayList<>();
            for (String id : ids) {
                if (StringUtils.isNotBlank(id)) {
                    idList.add(id);
                }
            }
            if (idList.size() > 0) {
                //批量更新消息已签收
                List<ChatMsg> chatMsgList = userService.findChatMsgListByIds(idList);
                for(ChatMsg chatMsg : chatMsgList){
                    chatMsg.setSignFlag(MsgSignEnum.SIGNED.getCode());
                }
                userService.updateChatMsgList(chatMsgList);
            }


        } else if (ActionEnum.KEEP_ALIVE.getCode().equals(action)) {
            //心跳

        }
        channels.writeAndFlush(new TextWebSocketFrame());
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
    }
}
